<?php
declare (strict_types = 1);
namespace app\user\service\user\admin;

use app\common\service\BaseService;
use app\user\logic\user\admin\VipUser as VipUserLogic;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageForm;
use eduline\admin\page\PageList;
use think\facade\Request;

/**
 * vip用户
 */
class VipUser extends BaseService
{
    /**
     * 用户列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-15
     */
    public function index()
    {
        // 搜索功能
        $map = [];
        if (request()->is_platform) {
            Request::has('mhm_id', 'get', true) && $map['mhm_id'] = Request::get('mhm_id/d');
        } else {
            $map['mhm_id'] = request()->user->mhm_id;
        }

        Request::has('phone', 'get', true) && $map['phone'] = Request::get('phone/s', '');
        $data                                               = app(VipUserLogic::class)->getList($map)->bindAttr('user', ['avatar_url', 'nick_name', 'phone']);
        // 定义字段
        $keyList = [
            'user'        => ListItem::make('custom')->title('基本信息')->width(100),
            'vip_status'  => ListItem::make('custom')->title('会员状态'),
            'expire_time' => ListItem::make()->title('过期时间'),
            'create_time' => ListItem::make()->title('首次开通时间'),
            'update_time' => ListItem::make()->title('最近续费时间'),
        ];

        $searchKey = [
            'mhm_id' => FormItem::make('searchSchool')->title(false)->visible(request()->is_platform),
            'phone'  => FormItem::make('input')->title(false)->placeholder('手机号')->maxlength(11),
        ];

        // 设置表单
        $list = app(PageList::class);
        // 表单字段
        $list->pageKey   = $keyList;
        $list->searchKey = $searchKey;
        $list->datas     = $data;

        return $list->send();
    }

    /**
     * 赠送会员
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-15
     * @return   [type]                         [description]
     */
    public function edit(int $id)
    {
        if (Request::isPut()) {
            $data = Request::put();
            $user = app(VipUserLogic::class)->editVip($id, $data);

            return $this->parseToData($user, 1, '编辑成功');
        }

        $datas = app(VipUserLogic::class)->with(['user'])->where('id', $id)->findOrFail()->bindAttr('user', ['nick_name', 'phone']);
        // 定义字段
        $keyList = [
            'nick_name'   => FormItem::make()->title('昵称')->disabled(),
            'phone'       => FormItem::make()->title('手机号')->disabled(),
            'expire_time' => FormItem::make('date')->title('过期时间')->required(),
        ];
        // 设置表单
        $form = app(PageForm::class);
        // 表单字段
        $form->pageKey     = $keyList;
        $form->datas       = $datas;
        $form->saveMethod  = 'PUT';
        $form->savePostUrl = '/user/admin/account/vip/' . $id . '/edit';

        return $form->send();
    }
}
